import type { Ref } from 'vue';
import { onBeforeUnmount, onMounted } from 'vue';
import { findDOMNode } from '../../_util/props-util';

export default function useSelectTriggerControl(
  refs: Ref[],
  triggerOpen: (open: boolean) => void,
) {
  function onGlobalMouseDown(event: MouseEvent) {
    let target = event.target as HTMLElement;

    if (target.shadowRoot && event.composed) {
      target = (event.composedPath()[0] || target) as HTMLElement;
    }
    const elements = refs.map(e => findDOMNode(e.value))
    const isOutside = elements.every(element => !element?.contains(target))
    if (isOutside) {
      triggerOpen(false);
    }
  }

  onMounted(() => {
    window.addEventListener('mousedown', onGlobalMouseDown);
  });

  onBeforeUnmount(() => {
    window.removeEventListener('mousedown', onGlobalMouseDown);
  });
}
